package com.yuzhi.generate.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.yuzhi.common.annotation.Log;
import com.yuzhi.common.core.controller.BaseController;
import com.yuzhi.common.core.domain.ApiResult;
import com.yuzhi.common.core.domain.PageQuery;
import com.yuzhi.common.core.domain.request.CollectRequest;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.enums.BusinessTypeEnum;
import com.yuzhi.generate.entity.SysGenTable;
import com.yuzhi.generate.entity.SysGenTableColumn;
import com.yuzhi.generate.entity.dto.SysGenTableReq;
import com.yuzhi.generate.service.ISysGenTableService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 代码生成 操作处理
 * @Author: sunshine
 * @Date: 2024-02-28
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {

    private final ISysGenTableService genTableService;

    /**
     * 查询代码生成列表
     */
    @SaCheckPermission("tool:gen:page")
    @PostMapping("/page")
    public ApiResult<PageDataInfo<SysGenTable>> genPage(@RequestBody SysGenTableReq request) {
        return ApiResult.ok(genTableService.selectPage(request));
    }

    /**
     * 查询代码生成业务
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:query")
    @GetMapping(value = "/{tableId}")
    public ApiResult<Map<String, Object>> getInfo(@PathVariable String tableId) {
        SysGenTable table = genTableService.selectById(tableId);
        List<SysGenTable> tables = genTableService.selectGenTableAll();
        List<SysGenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return ApiResult.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @SaCheckPermission("tool:gen:list")
    @PostMapping("/db/list")
    public ApiResult<PageDataInfo<SysGenTable>> dataList(@RequestBody SysGenTableReq request) {
        return ApiResult.ok(genTableService.selectPageDbTable(request, request.getPageQuery()));
    }

    /**
     * 批量修代码生成路径
     *
     * @param sysGenTableReq
     */
    @SaCheckPermission("tool:gen:edit")
    @PostMapping(value = "/updatePackageName")
    public ApiResult<Void> updatePackageName(@RequestBody SysGenTableReq sysGenTableReq) {
        genTableService.updatePackageName(sysGenTableReq.getTableNames(), sysGenTableReq.getPackageName());
        return ApiResult.ok();
    }

    /**
     * 查询数据表字段列表
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:list")
    @GetMapping(value = "/column/{tableId}")
    public ApiResult<PageDataInfo<SysGenTableColumn>> columnList(@PathVariable("tableId") String tableId) {
        PageDataInfo<SysGenTableColumn> dataInfo = new PageDataInfo<>();
        List<SysGenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
        dataInfo.setList(list);
        dataInfo.setTotalCount(list.size());
        return ApiResult.ok(dataInfo);
    }

    /**
     * 导入表结构（保存）
     *
     * @param tableNames 表名串
     */
    @SaCheckPermission("tool:gen:import")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.IMPORT)
    @PostMapping("/importTable")
    public ApiResult<Void> importTableSave(@RequestBody CollectRequest<String> tableNames) {
        // 查询表信息
        List<SysGenTable> tableList = genTableService.selectDbTableByNames(tableNames.getArray());
        genTableService.importGenTable(tableList);
        return ApiResult.ok();
    }

    /**
     * 修改保存代码生成业务
     */
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public ApiResult<Void> editSave(@Validated @RequestBody SysGenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return ApiResult.ok();
    }

    /**
     * 删除代码生成
     *
     * @param tableIds 表ID串
     */
    @SaCheckPermission("tool:gen:remove")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{tableIds}")
    public ApiResult<Void> remove(@PathVariable String[] tableIds) {
        genTableService.deleteByIds(tableIds);
        return ApiResult.ok();
    }

    /**
     * 预览代码
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    public ApiResult<Map<String, String>> preview(@PathVariable("tableId") String tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return ApiResult.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableName 表名
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public ApiResult<Void> genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return ApiResult.ok();
    }

    /**
     * 同步数据库
     *
     * @param tableName 表名
     */
    @SaCheckPermission("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.UPDATE)
    @GetMapping("/synchDb/{tableName}")
    public ApiResult<Void> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return ApiResult.ok();
    }

    /**
     * 批量生成代码
     *
     * @param tables 表名串
     */
    @SaCheckPermission("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GENCODE)
    @PostMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response,@RequestBody CollectRequest<String> tables) throws IOException {
        byte[] data = genTableService.downloadCode(tables.getArray());
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), false, data);
    }
}
